<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box {
      width: 100px;
      height: 100px;
      border: 1px solid #000;
      background-color: #409eff;
      text-align: center;
      font-size: 12px;
      border-radius: 5px;
      transform: translate(0, 0);
    }

    .target {
      position: absolute;
      right: 20px;
      top: 20px;
      width: 300px;
      height: 300px;
      border: 3px dotted red;
      color: gray;
      text-align: center;
      line-height: 300px;
    }

    .active {
      border: 3px dotted blue;
    }

    #img-wyb {
      width: 100px;
      height: 100px;
    }
  </style>
</head>

<body>
  <div id="container" class="container">
    <div class="box" draggable="true">我可以在页面上随便拖</div>
    <img id="img-wyb" src="img/test.jpeg" alt="">
  </div>
  <div id="target" class="target">目标区域</div>
  <script>
    const containerEle = document.getElementById("container")
    const targetEle = document.getElementById("target")
    const drag = function (ele, target) {
      let mouseDiff = null
      // dragend事件触发有延迟，出现在拖动到可拖动区域之外时
      // 解决：https://qa.1r1g.com/sf/ask/4323252881/
      // document.addEventListener("dragover", function (event) {
      //   event.preventDefault();
      // }, false);
      ele.addEventListener("dragstart", (e) => {
        console.log('dragstart', e)
        mouseDiff = `translate(${-e.offsetX}px, ${-e.offsetY}px)`
        e.dataTransfer.effectAllowed = 'move'
        e.dataTransfer.setData('text/plain', '移进来')
      })
      ele.addEventListener('dragend', (e) => {
        // console.log("dragend")
        // 元素自身的transform
        const startPosition = window.getComputedStyle(e.target).transform
        // 鼠标移动了多少
        const mouseMove = `translate(${e.offsetX}px, ${e.offsetY}px)`
        // console.log(startPosition, mouseMove, mouseDiff)
        e.target.style.transform = `${startPosition} ${mouseDiff} ${mouseMove} `
      })
      targetEle.addEventListener("dragenter", (e) => {
        // console.log('dragenter')
        // console.log(target.classList)
        target.classList.add('active')
      })
      targetEle.addEventListener("dragover", (e) => {
        e.preventDefault()
        // console.log('dragover')
      })
      targetEle.addEventListener("dragleave", (e) => {
        // console.log('dragenter')
        // console.log(target.classList)
        target.classList.remove('active')
      })
      targetEle.addEventListener("drop", (e) => {
        console.log('drop', e)
        const data = e.dataTransfer.getData('text/plain')
        console.log(data)
        e.target.innerText = data
      })
    }
    drag(containerEle, targetEle)
  </script>
</body>

</html>